<template>
  <n-scrollbar x-scrollable style="max-height: 100vh">
    <CommonPage show-footer>
      <div>
        <n-form ref="chapterInfoRef" :model="chapterInfoValue" :rules="rules" size="small" :label-width="180" inline >
          <n-form-item label="" path="input">
            <div >
              <div style="display: flex; align-items: center; margin-bottom: 20px;">
                <span>选择课程:</span>
                <n-auto-complete
                    style="width: 210px;margin-left: 15px"
                    v-model:value="chapterInfoValue.name"
                    :options="options"
                    placeholder=""
                    @input="handleInput"
                    @blur="handSelect(chapterInfoValue.name)"
                    @select="handleSelect"
                    clearable
                />
                <span style="width: 70px;margin-left: 15px">章节名称：</span>
                <n-input style="margin-left: 15px;width: 200px" v-model:value="chapterInfoValue.chapterName" placeholder=""></n-input>
                <n-button type="primary" style="margin-left: 10px;" @click="sub">搜索</n-button>
                <n-button type="primary" size="small" @click="onAdd" style="margin-left: 10px">添加章节</n-button>
              </div>
            </div>
          </n-form-item>
        </n-form>
      </div>
      <n-data-table
          remote
          :single-line="false"
          ref="table"
          :columns="columns"
          :data="chapterList"
          :loading="loading"
          :pagination="paginationReactive"
          :row-key="rowKey"
          @update:page="onChangePage"
          @update:page-size="onUpdatePageSize"
      />

    </CommonPage>
  </n-scrollbar>
</template>

<script setup>
import {  ref, reactive, onMounted,watch } from 'vue'
import api from '@/api/admin';
import ChapterActions from './components/chapter-actions.vue';
import { useUserStore } from '@/store';
import { useRouter } from 'vue-router';
const userStore = useUserStore()
const router = useRouter()
const rules=ref(null)
const select=ref(0)
const watchs=ref(0)
const name=ref('')
const chapterInfoRef = ref(null)
const loading =  ref(true)
const chapterList = ref([])
const options =  ref([])
const onAdd = ()=>{
  router.push({name: 'AdminChapterAdd'})
}
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [5, 10, 20, 50],
  prefix ({ itemCount }) {
    return `总共 ${itemCount} 条`
  }
})
const chapterInfoValue = ref({
  name: '',
  code:'',
  chapterName:'',
  pageNum:paginationReactive.page,
  pageSize:paginationReactive.pageSize,
});
const columns = [
  {
    key: 'name',
    title: '课程名称',
    width: '120',
  },
  {
    key: 'chapterName',
    title: '章节名称',
    width: '120',
  },
  {
    key: 'actions',
    title: '操作',
    width: '200',
    render(row) {
      return h(
          ChapterActions,
          {
            onClickDelete: () => onDeleteChapter(row),
            onClickEdit: () => onEditChapter(row),
          }
      );
    }
  }
]
const queryByPage = async (currentPage)=>{
  loading.value = true
  try {
    chapterInfoValue.value.pageSize=paginationReactive.pageSize
    chapterInfoValue.value.pageNum=currentPage
    if (chapterInfoValue.value.name!=='' && chapterInfoValue.value.code===''){
      const res = await api.findChaptersByCourseChapterName(
          {
            ...chapterInfoValue.value
          }
      )
      const {pageNum, pageSize, total, list} = res.data
      paginationReactive.page = pageNum
      paginationReactive.pageSize = pageSize
      paginationReactive.itemCount = total
      chapterList.value = list.map((item, i) => {
        return item;
      })
    }else {
      const res = await api.findAllChapters(
          {
            ...chapterInfoValue.value
          }
      )
      const {pageNum, pageSize, total, list} = res.data
      paginationReactive.page = pageNum
      paginationReactive.pageSize = pageSize
      paginationReactive.itemCount = total
      chapterList.value = list.map((item, i) => {
        return item;
      })
    }
  } catch (err) {
  }finally{
    loading.value = false
  }
}
const handleSelect = async (value) => {
  loading.value = true;
  select.value=1
  chapterInfoValue.value.code=value
  chapterInfoValue.value.pageNum=1
  if (chapterInfoValue.value.name==='' ||chapterInfoValue.value.name===null){
    chapterInfoValue.value.code=''
  }
  try {
    const res = await api.findAllChapters({
      ...chapterInfoValue.value
    });
    const {pageNum, pageSize, total, list} = res.data
    paginationReactive.page = pageNum
    paginationReactive.pageSize = pageSize
    paginationReactive.itemCount = total
    chapterList.value = list.map((item,i)=>{return item;})
  } catch (err) {
  } finally {
    loading.value = false;
  }
};
const handSelect=async (value)=>{
    if (watchs.value !== 1) {
        if (chapterInfoValue.value.code === '' && select.value === 0) {
        loading.value = true;
        chapterInfoValue.value.name = value
        chapterInfoValue.value.pageNum = 1
        try {
          const res = await api.findChaptersByCourseChapterName({
            ...chapterInfoValue.value
          })
          chapterInfoValue.value.code = ''
          const {pageNum, pageSize, total, list} = res.data
          paginationReactive.page = pageNum
          paginationReactive.pageSize = pageSize
          paginationReactive.itemCount = total
          chapterList.value = list.map((item, i) => {
            return item;
          })
        } catch (err) {
        } finally {
          loading.value = false;
        }
      }
    }
};
const handleInput = async (e) => {
  if (name.value!==''&&select.value===1 && watchs.value===1){
    select.value=0
    watchs.value=0
    chapterInfoValue.value.code=''
  }
  try {
    const res = await api.findCourseBycourseName({
      name: chapterInfoValue.value.name,
    });
    const list  = res.data;
    const transformedData = list.map(item => ({
      label: item.name,
      value: item.code,
    }));
    options.value = transformedData;
  } catch (err) {
  } finally {
  }
};
watch(select,(value)=>{
  if (value===1){
    name.value=chapterInfoValue.value.name
    watchs.value = 1
  }
})
const onChangePage =  (page) => {
  paginationReactive.page = page;
  if (!loading.value) {
    queryByPage(page)
  }
}
const onDeleteChapter = async (courses)=>{
  const {id} = courses
  try {
    await api.deleteChapter({id})
    $message.success("删除成功")
    if (!loading.value) {
      await queryByPage(paginationReactive.page)
    }
  }catch (err){
    $message.error("删除失败")
  }
}
const onEditChapter = async (courses)=>{
  const {id} = courses
  router.push({name: 'AdminChapterEdit',params:{chId: id}})
}
const sub = async ()=>{
  loading.value = true;
  try {
    if (chapterInfoValue.value.name==='' ||chapterInfoValue.value.name===null){
      chapterInfoValue.value.code=''
    }
    chapterInfoValue.value.pageNum=1
    if (select.value===1){
      const res = await api.findAllChapters({
        ...chapterInfoValue.value
      });
      const {pageNum, pageSize, total, list} = res.data
      paginationReactive.page = pageNum
      paginationReactive.pageSize = pageSize
      paginationReactive.itemCount = total
      chapterList.value = list.map((item,i)=>{return item;})
    }else {
      const res = await api.findChaptersByCourseChapterName({
        ...chapterInfoValue.value
      });
      const {pageNum, pageSize, total, list} = res.data
      paginationReactive.page = pageNum
      paginationReactive.pageSize = pageSize
      paginationReactive.itemCount = total
      chapterList.value = list.map((item,i)=>{return item;})
    }
  } catch (err) {
  } finally {
    loading.value = false;
  }
}
const onUpdatePageSize = (pageSize) => {
  paginationReactive.pageSize = pageSize;
  paginationReactive.page = 1;
  queryByPage(1)
}
const rowKey = (rowData) => {
  return rowData.id
}
onMounted(()=>{
  queryByPage(paginationReactive.page)
})
watch(
    ()=>router.currentRoute.value.fullPath,
    ()=>{
      if (router.currentRoute.value.fullPath==='/admin/course/chapter-list') {
        queryByPage(paginationReactive.page)
      }
    }
)
</script>
